package zblibrary.facechat.modules.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProvider;

import lingxi.common.okhttp.ResultCallback;
import lingxi.common.result.Result;
import lingxi.entity.UserInfo;
import me.cl.library.base.BaseActivity;

import lingxi.viewmodel.UserViewModel;
import okhttp3.Call;
import zblibrary.facechat.R;
import zblibrary.facechat.modules.home.MainActivity;
import zblibrary.facechat.util.SharedPreferencesUtils;

public class RegisterActivity extends BaseActivity {
    //布局内的控件
    private EditText et_name;
    private EditText et_reg_pw1;
    private EditText et_reg_pw2;
    private EditText et_reg_phone;
    private Button mRegBtn;

    private LoadingDialog mLoadingDialog; //显示正在加载的对话框
    private UserViewModel mUserViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initViews();
        initViewModel();
    }

    private void initViewModel() {
        mUserViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        mUserViewModel.getTipMessage().observe(this, tipMessage -> {
            if (tipMessage.isRes()) {
                showToast(tipMessage.getMsgId());
            } else {
                showToast(tipMessage.getMsgStr());
            }
        });
    }

    private void register() {
        //先做一些基本的判断，比如输入的用户命为空，密码为空，网络不可用多大情况，都不需要去链接服务器了，而是直接返回提示错误
        if (getAccount().isEmpty()){
            showToast("你输入的账号为空！");
            return;
        }
        if (getPassword1().isEmpty() || getPassword2().isEmpty()){
            showToast("你输入的密码为空！");
            return;
        }
        if (!getPassword1().equals(getPassword2())){
            showToast("两次输入的密码不一致！");
            return;
        }
        //登录一般都是请求服务器来判断密码是否正确，要请求网络，要子线程
        showLoading();//显示加载框
        String username = getAccount();
        String password1 = getPassword1();
        String password2 = getPassword1();
        String phone = getPhone();
        mUserViewModel.doRegister(username, password1, password2, phone, null, new ResultCallback<Result<UserInfo>>() {
            @Override
            public void onSuccess(Result<UserInfo> response) {
                //判断账号和密码
                hideLoading();//隐藏加载框
                String code = response.getCode();
                showToast("返回码:"+code);
                if (code.equals("0")) {
                    showToast("注册成功");
                    loadUserName();    //无论如何保存一下用户名
                    //置空密码即可
                    //获取SharedPreferences对象，使用自定义类的方法来获取对象
                    SharedPreferencesUtils helper = new SharedPreferencesUtils(RegisterActivity.this, "setting");
                    //创建记住密码和自动登录是默认不选,密码为空
                    helper.putValues(
                            new SharedPreferencesUtils.ContentValue("remenberPassword", false),
                            new SharedPreferencesUtils.ContentValue("autoLogin", false),
                            new SharedPreferencesUtils.ContentValue("password", ""));
                    startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    finish();//关闭页面
                } else {
                    String msg = response.getMsg();
                    showToast("失败原因:"+msg);
                }
            }
            @Override
            public void onError(Call call, Exception e) {
                hideLoading();//隐藏加载框
            }
        });
    }

    /**
     * 隐藏加载的进度框
     */
    public void hideLoading() {
        if (mLoadingDialog != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLoadingDialog.hide();
                }
            });

        }
    }

    /**
     * 显示加载的进度款
     */
    public void showLoading() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this, getString(R.string.loading), false);
        }
        mLoadingDialog.show();
    }

    /**
     * 是否可以点击登录按钮
     *
     * @param clickable
     */
    public void setRegBtnClickable(boolean clickable) {
        mRegBtn.setClickable(clickable);
    }

    /**
     * 获取账号
     */
    public String getAccount() {
        String res = et_name.getText().toString().trim();//去掉空格
        return res;
    }

    public String getPassword1() {
        String res = et_reg_pw1.getText().toString().trim();//去掉空格
        return res;
    }

    public String getPhone() {
        String res = et_reg_phone.getText().toString().trim();//去掉空格
        return res;
    }

    public String getPassword2() {
        String res = et_reg_pw2.getText().toString().trim();//去掉空格
        return res;
    }

    public void showToast(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initViews() {
        mRegBtn = (Button) findViewById(R.id.btn_reg_done);
        mRegBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                register();
            }
        });
        et_name = (EditText) findViewById(R.id.et_reg_account);
        et_reg_pw1 = (EditText) findViewById(R.id.et_reg_pw1);
        et_reg_pw2 = (EditText) findViewById(R.id.et_reg_pw2);
        et_reg_phone = (EditText) findViewById(R.id.et_reg_phone);
    }

    /**
     * 保存用户账号
     */
    public void loadUserName() {
        if (!getAccount().equals("") || !getAccount().equals("请输入登录账号")) {
            SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting");
            helper.putValues(new SharedPreferencesUtils.ContentValue("name", getAccount()));
        }

    }
}
